package com.imau.controller;

import com.imau.bean.Book;
import com.imau.common.entity.ResultCode;
import com.imau.common.entity.ResultEntity;
import com.imau.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
@Api(value = "图书管理")
public class BookController {


    @Autowired
    private BookService bookService;

    @PostMapping
    @ApiOperation(value = "添加图书", notes = "添加图书",httpMethod = "POST",response = ResultEntity.class)
    public ResultEntity saveBook(@RequestBody Book book)
    {
         boolean flag = bookService.save(book);
        return flag ? ResultEntity.SUCCESS() : ResultEntity.FAIL();
    }

    @PutMapping
    public ResultEntity editBook(@RequestBody Book book)
    {
        boolean flag = bookService.update(book);
        return flag ? ResultEntity.SUCCESS() : ResultEntity.FAIL();
    }


    @DeleteMapping("/{id}")
    public ResultEntity deleteById(@PathVariable Integer id)
    {
        boolean flag = bookService.delete(id);
        return flag ? ResultEntity.SUCCESS() : ResultEntity.FAIL();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "按照Id查询图书", notes = "按照Id查询图书",httpMethod = "GET",response = Book.class)
    public ResultEntity findBookById(@PathVariable Integer id)
    {

       Book book =  bookService.getById(id);

        return book !=null ? new ResultEntity(ResultCode.SUCCESS,book):new ResultEntity(ResultCode.NODATA);
    }


    @GetMapping()
    public ResultEntity findAll()
    {

        System.out.println("findAll....");
        List<Book> books=bookService.getAll();

        return books !=null ? new ResultEntity(ResultCode.SUCCESS,books):new ResultEntity(ResultCode.NODATA);
    }

//    @GetMapping("/{bookName}")
//    public ResultEntity findAllByName(@PathVariable String bookName)
//    {
//
//        List<Book>  books=bookService.getAll(bookName);
//
//        return books !=null ? new ResultEntity(ResultCode.SUCCESS,books):new ResultEntity(ResultCode.NODATA);
//    }
}
